#User Class: Deals with log-in and sending / recieving messages
#Last updated on: 16/06/06 @ 7:00PM
import xmpp
import os
import signal
import time
import sys

class TestUser:
    def __init__(self, some_jid, some_pwd):
        self.jid = some_jid
        self.pwd = some_pwd

    # This method logs the user into their jabber account        
    def signIn(self):
        self.jid = xmpp.protocol.JID(self.jid) #sets jabber ID
        self.client = xmpp.Client(self.jid.getDomain(), debug = []) #Creates a client

        if self.client.connect() == "":
            print "not connected"
            sys.exit(0) #Needs to change to a warning, currently exits system

        if self.client.auth(self.jid.getNode(), self.pwd) == None:
            print "authentication failed"
            sys.exit(0) #Needs to change to a warning or provide another option, currently exits system

        self.client.sendInitPresence() #Shows server client is online

    # This method sends a jabber recipient a message
    def sendMsge(self, recipient, some_msg):
        self.msg = some_msg
        self.client.send(xmpp.protocol.Message(recipient,self.msg))

    # This method is used by recieveMsg, it prints the retrieved message
    #   as well as showing the user that someone is currently typing a message
    def messageCB(self, conn, msg):
        if msg.getBody() == None:
            print str(xmpp.protocol.JID(msg.getFrom()).getNode()) + " is typing a message"
        if msg.getBody() != None:
            msg.setTimestamp(time.strftime("%H:%M:%S"))
            print "Time of message: " + str(msg.getTimestamp())
            print "Sender: " + str(xmpp.protocol.JID(msg.getFrom()).getStripped())
            print "Content: " + str(msg.getBody())
            # Sends a pre-set reply to all senders
            self.client.send(msg.buildReply("I am not here right now"))
            msg = None

    # This method is used by GoOn, it keeps the connection running
    def StepOn(self, conn):
        try:
            conn.Process(1)
        except KeyboardInterrupt:
            return 0
        return 1
      
    # This method is used by recieveMsg, it checks for a running connection
    def GoOn(self, conn):
        while self.StepOn(conn):
            pass
        
    # This method retrieves any incoming messages
    def recieveMsge(self):
        self.client.RegisterHandler('message', self.messageCB)
        self.GoOn(self.client) 

    # This method retrieves a full contact list:
    def printContacts(self):
        # get the roster (contact list)
        self.r = self.client.getRoster()
        # make a list of contacts:
        contacts = self.r.getItems()
##        for item in contacts:
##            print item +", ",
##            
##        print ""

        for contact in contacts:
            status = self.r.getStatus(contact)
            show = self.r.getShow(contact)
            sb = self.r.getSubscription(contact)
            priority = self.r.getPriority(contact)
            print contact, priority, status, show, sb
            
        """The following is a test:    
        (1) Prints a specific contacts personal status message
        (2) Prints the contacts "show" AKA status (away, online, etc) (assumed to be the status, not sure)
        (3) Prints the contacts display name"""

##        #Test (1)
##        print "klh11@jabber.sfu.ca's status: " + self.r.getStatus("klh11@jabber.sfu.ca")
##        #Test (2)
##        print self.r.getShow("klh11@jabber.sfu.ca")
##        #Test (3)
##        print self.r.getName("klh11@jabber.sfu.ca")
##        #End of testing

    def checkSubscriptionRequests(self):
           self.client.RegisterHandler("presence",self.presenceHandler)
           self.GoOn(self.client) 

    def addBuddy(self, buddyJid):
        realJid = xmpp.protocol.JID(buddyJid)
        self.r.Subscribe(realJid.getStripped())
        #self.r.Authorize(buddyJid)
        #self.r.request()

    def seeSubscription(self, buddyJid):
        self.r.getSubscription(buddyJid)
        
    def removeBuddy(self, buddyJid):
        realJid = xmpp.protocol.JID(buddyJid)
        self.r.delItem(realJid.getStripped())
        #self.r.request()
        #self.r.Unsubscribe(buddyJid)
        #self.r.Unauthorize(buddyJid)

    def presenceHandler(self, client,event):
       '''Handle presence event'''
       fromJID  = xmpp.protocol.JID(event.getFrom())
       presType = event.getType()
       if presType == 'subscribe':
           # if you want to add them:
           self.client.sendPresence(fromJID.getStripped(),'subscribed')
           # if not:
           print "buddy added"
           #self.client.sendPresence(to=fromJID,typ='unsubscribed')

"""Roster requests:"""
##   def accept(self, buddy):
##        buddyJid = cmpp.protocol.JID(buddy)
##        reply = xmpp.protocol.Presence(to=buddyJid.getStripped(), typ="subscribed")
##        self.jabber.send(reply)

##    def reject(self, buddy):
##        buddyJid = cmpp.protocol.JID(buddy)
##        reply = xmpp.protocol.Presence(to=buddyJid.getStripped(), typ="unsubscribed")
##        self.jabber.send(reply)

        
        
            
        
        
        
        
        
